/*
 * Copyright (C) RT, 2017 by kiterunner_t
 * TO THE HAPPY FEW
 */

package com.zgys.mes.rest;

import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.zgys.mes.util.Log;
import com.zgys.mes.util.error.RtErrorEnum;
import com.zgys.mes.util.error.RtException;
import com.zgys.mes.util.error.RtResponse;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class RestExceptionHandler {
    private static final RtException serverInternalEx = new RtException(RtErrorEnum.ERROR_INTERNAL_SERVER);

    @ExceptionHandler(value = RtException.class)
    public RtResponse handleDataStoreException(HttpServletResponse response, RtException ex) {
        Log.warn("Rt Server Exception.", ex);
        RtErrorEnum error = RtErrorEnum.getEnum(ex.getCode());
        try {
            switch (error) {
                case SUCCESS:
                case SUCCESS_MULTIPLE_CHOICE:
                case SUCCESS_RESOURCE_TRANSFER:
                case ERROR_BAD_REQUEST:
                case ERROR_UNAUTHORIZED:
                case ERROR_FORBIDDEN:
                case ERROR_NOT_FOUND:
                    response.sendError(error.getCode(),error.getMessage());
                    break;
                default:
                    response.sendError(RtErrorEnum.ERROR_INTERNAL_SERVER.getCode(), RtErrorEnum.ERROR_INTERNAL_SERVER.getMessage());
            }
        } catch (IOException e) {
            Log.warn("Response sendError Exception.", e);
            response.setStatus(RtErrorEnum.ERROR_INTERNAL_SERVER.getCode());
        }
        return new RtResponse(ex);
    }


    @ExceptionHandler(value = DataAccessException.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public RtResponse handleDaoException(DataAccessException ex) {
        Log.warn("Server Exception.", ex);
        return new RtResponse(RtErrorEnum.ERROR_DB);
    }


    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(code = HttpStatus.INTERNAL_SERVER_ERROR)
    public RtResponse runtimeExceptionHandler(Exception ex) {
        Log.error("Server Exception. Message", ex);
        return new RtResponse(serverInternalEx);
    }
}

